var apis = require( '../../cloud/lib/apis' );
var rongrequest = require( '../../cloud/lib/rongrequest' );
var redisServer=require( '../../cloud/redis/redisServer' );
var moment = require("moment");
var common   = require( '../../cloud/common' );
var AV = require('leanengine');
exports.kuaidiSearch=kuaidiSearch;
function kuaidiSearch( com, nu,callback ) {
	//rongrequest.kuaidiSearch( apis['kuaidi']['searchUrl'], {
	//	id : '105428',
	//	secret   : '8d9309deb4a3c1144268c4aca1d07748',
	//	com : com,
	//	nu    : nu,
	//	type:'json',
	//	encode:'utf8',
	//	ord:'desc'
	//}, function( err, resultText ) {
	//	return callback( err, resultText );
	//} );

	if(com == "kuaijie"){
		com = "kuaijiesudi";
	}

	if(com == "quanfeng"){
		com = "quanfengkuaidi";
	}

	if(com == "huitong"){
		com = "huitongkuaidi";
	}

	if(com == "debang"){
		com = "debangwuliu";
	}

	if(com == "yousu"){
		com = "youshuwuliu";
	}

	if(com == "pingyou"){
		com = "youzhengguonei";
	}

	if(com == "guotong"){
		com = "guotongkuaidi";
	}


	rongrequest.kuaidiSearch("http://m.kuaidi100.com/query", {
		type:com,
		postid:nu
	}, function( err, resultText ) {
		return callback( err, resultText );
	} );



	//rongrequest.kuaidiSearch( "http://biz.trace.ickd.cn/"+com+"/"+nu, {
    //
	//	}, function( err, resultText ) {
	//		return callback( err, resultText );
	//	} );

	//备用快递查询：kdpt
	//	rongrequest.kuaidiSearch("http://q.kdpt.net/api", {
	//	id : 'kDWsys86b125uas091aA966984',
	//	com : com,
	//	nu    : nu,
	//	show:'json',
	//	format:'ickd',
	//	ord:'desc'
	//}, function( err, resultText ) {
	//	return callback( err, resultText );
	//} );
}
//获取订单物流信息
exports.getOrderLogistice = function(orderObj,callback ){
	var logisticeObj={};
	logisticeObj["status"]="-1";
	logisticeObj["statusVal"]=apis["logisticeStatus"][logisticeObj["state"]];
	logisticeObj["expIcon"]="";
	logisticeObj["message"]="";
	logisticeObj["errCode"]="0";
	logisticeObj["data"]=[];
	logisticeObj["html"]="";
	logisticeObj["mailNo"]="";
	logisticeObj["expTextName"]="";
	logisticeObj["expSpellName"]="";
	logisticeObj["update"]="";
	logisticeObj["cache"]="";
	logisticeObj["ord"]="";
	logisticeObj["tel"]="";
	//无效订单
	if(orderObj==null||orderObj==""||orderObj==undefined){
		logisticeObj["message"]="无效的订单";
		return callback(logisticeObj);
	}else{
		//是否发货
		if(orderObj.get("status")<=apis["order"]["status_noSend"]||orderObj.get("deliverTime")==null){
			logisticeObj["message"]="订单没有发货信息";
			return callback(logisticeObj);
		}else{
			if(orderObj.get("logisticsComCode")=="-1"){
				logisticeObj["message"]="无需物流，"+common.formatDateNormal(orderObj.get("deliverTime"),null)+"已发货";
				return callback(logisticeObj);
			}else{
				var com=orderObj.get("logisticsComCode");//物流公司编码
				var nu=orderObj.get("expressCode");//物流单号
				logisticeObj["mailNo"]=nu;
				logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");

				//如果订单中物流信息为空
				var logisticeData=orderObj.get("logisticsData");
				if(logisticeData==""||logisticeData==null||logisticeData==undefined){
					kuaidiSearch(com,nu,function(err,result){

						var tempResult=(result.text.replace("/**/&&","").replace("(","").replace(")",""));
						orderObj.set("logisticsTime",new Date());
						logisticeObj=JSON.parse(tempResult);
						logisticeObj["statusVal"]=apis["logisticeStatus"][logisticeObj["state"]];
						logisticeObj["expIcon"]=apis["logisticeIcon"][orderObj.get("logisticsComCode")];
						logisticeObj["errCode"]="0";
						logisticeObj["mailNo"]=nu;
						logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");
						logisticeObj["orderCode"] = orderObj.get("orderCode");
						logisticeObj["createOrderTime"] = moment(orderObj.createdAt).format('YYYY-MM-DD HH:mm:ss');
						orderObj.set("logisticsData",JSON.stringify(logisticeObj));
						orderObj.save();


						return callback(logisticeObj);
					})
				}
				else{
					//物流信息是否是最终信息(签收或退回)，是的话直接返回
					logisticeData=JSON.parse(logisticeData);
					if(logisticeData.status=="3"||logisticeData.status=="4"){
						logisticeObj=logisticeData;
						logisticeObj["statusVal"]=apis["logisticeStatus"][logisticeObj["status"]];
						logisticeObj["expIcon"]=apis["logisticeIcon"][orderObj.get("logisticsComCode")];
						logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");
						logisticeObj["orderCode"] = orderObj.get("orderCode");
						logisticeObj["createOrderTime"] = moment(orderObj.createdAt).format('YYYY-MM-DD HH:mm:ss');
						return callback(logisticeObj);
					}
					//否则判断物流信息是否过期，没过期的直接返回(设置30分钟缓存时间)
					else{
						if(new Date().getTime()-orderObj.get("logisticsTime").getTime()<30*60*1000){
							logisticeObj=logisticeData;
							logisticeObj["statusVal"]=apis["logisticeStatus"][logisticeObj["state"]];
							logisticeObj["expIcon"]=apis["logisticeIcon"][orderObj.get("logisticsComCode")];
							logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");
							logisticeObj["orderCode"] = orderObj.get("orderCode");
							logisticeObj["createOrderTime"] = moment(orderObj.createdAt).format('YYYY-MM-DD HH:mm:ss');
							return callback(logisticeObj);
						}
						//过期则更新订单物流信息并返回
						else{
							kuaidiSearch(com,nu,function(err,result){
								if(err){
									logisticeObj["message"]=err;
									return callback(logisticeObj);
								}else{

									var tempResult=(result.text.replace("/**/&&","").replace("(","").replace(")",""));


									orderObj.set("logisticsTime",new Date());


									logisticeObj=JSON.parse(tempResult);
									logisticeObj["statusVal"]=apis["logisticeStatus"][logisticeObj["state"]];
									logisticeObj["expIcon"]=apis["logisticeIcon"][orderObj.get("logisticsComCode")];


									logisticeObj["errCode"]="0";
									logisticeObj["mailNo"]=nu;
									logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");
									logisticeObj["orderCode"] = orderObj.get("orderCode");
									logisticeObj["createOrderTime"] = moment(orderObj.createdAt).format('YYYY-MM-DD HH:mm:ss');
									orderObj.set("logisticsData",JSON.stringify(logisticeObj));
									orderObj.save();


									return callback(logisticeObj);
								}
							})
						}
					}
				}
			}
		}
	}
};
exports.findKudiDis=findKudiDis;
function findKudiDis(callback ) {
	var query = new AV.Query('Dictionary');
	query.equalTo("type", "10");
	query.ascending("sortNum");
	query.find({
		success : function(dictionaryObjects) {
		var jsonArr = [];
		for (var i= 0; i< dictionaryObjects.length; i++) {
			var dictionaryObj= common.getDictionaryInfo(dictionaryObjects[i]);
			jsonArr.push(dictionaryObj);
		}
		return callback(jsonArr);
		}
	});
}